/*
 * Copyright 2009 eBusinessInformation
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package com.excilys.ymca.service.zencontact;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;

import roboguice.inject.InjectResource;
import android.util.Log;

import com.excilys.ymca.R;
import com.excilys.ymca.model.Contact;
import com.excilys.ymca.model.ZenContact;
import com.excilys.ymca.service.ContactService;
import com.excilys.ymca.service.exception.ServiceException;
import com.excilys.ymca.util.LoggedInHttpClient;
import com.google.inject.Inject;
import com.google.inject.Provider;

public class ZenContactService implements ContactService {

    private static final String  TAG = ZenContactService.class.getSimpleName();

    @Inject
    private ObjectMapper         mapper;

    @Inject
    @LoggedInHttpClient
    private Provider<HttpClient> httpClientProvider;

    /**
     * Url du serveur distant mettant à disposition la liste de contacts.
     */
    @InjectResource(R.string.zencontact_host)
    private String               host;

    @Override
    public List<Contact> getContactList() throws ServiceException {

        HttpClient httpClient = httpClientProvider.get();

        String url = host + "/contact/listAsJson";

        HttpUriRequest request = new HttpGet(url);

        try {
            HttpResponse response = httpClient.execute(request);

            // Le stream sera fermé par Jackson
            InputStream is = response.getEntity().getContent();

            return mapper.readValue(is, new TypeReference<List<ZenContact>>() {});
        } catch (JsonParseException e) {
            Log.e(TAG, "Could not parse Json result", e);
            throw new ServiceException(R.string.parse_exception_contact_service_zen);
        } catch (IOException e) {
            Log.e(TAG, "Could not get Json content", e);
            throw new ServiceException(R.string.io_exception_contact_service_zen);
        }

    }
}
